﻿using SqlPerfomance.V2.DAL;
using SqlPerfomance.V2.DomainModel.Enums;
using SqlPerfomance.V2.DomainModel.Models;
using SqlPerfomance.V2.DomainModel.NodeTree.Interfaces;
using SqlPerfomance.V2.WpfClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SqlPerfomance.V2.WpfClient
{
	/// <summary>
	/// Interaction logic for MaterializedPath.xaml
	/// </summary>
	public partial class MaterializedPath : Window
	{
		public MaterializedPath(ConnectionStrings connectionString)
		{
			InitializeComponent();

			var mpRepo = new MaterializedPathTreeRepository();
			var tree = mpRepo.GetMaterializedPathData(connectionString, AppSettingsHelper.MpTableName).ToList();

			var treeView = CreateTree(tree);
			trvMenu.Items.Add(treeView);
		}

		private MpTreeViewNode CreateTree(List<MaterializedPathTreeExtensionNode> tree)
		{
			var root = tree.Where(t => t.ParentId == 0).First();
			MpTreeViewNode treeView = new MpTreeViewNode(root.Id, (long)root.ParentId, root.Name, root.Path, root.Level);
			tree.Remove(root);
			GetTreeViewData(treeView, tree);
			return treeView;
		}

		private void GetTreeViewData(MpTreeViewNode treeView, List<MaterializedPathTreeExtensionNode> tree)
		{
			var children = tree.Where(t => t.ParentId == treeView.Id).ToList();
			for (int i = 0; i < children.Count; i++)
			{
				var child = new MpTreeViewNode(children[i].Id, (long)children[i].ParentId, children[i].Name, children[i].Path, children[i].Level);
				treeView.Children.Add(child);
				GetTreeViewData(child, tree);
			}
		}
	}
}
